package com.ddwl.order.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.OrderEnum;
import com.ddwl.common.exception.CommonException;
import com.ddwl.common.exception.ExceptionCode;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.GateApi;
import com.ddwl.common.feign.api.GoodsApi;
import com.ddwl.common.feign.api.ShopApi;
import com.ddwl.common.feign.api.UserApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.order.dao.OrderAddrDao;
import com.ddwl.order.dao.model.OrderAddr;
import com.ddwl.order.dao.model.OrderInfo;
import com.ddwl.order.dao.model.OrderSpu;
import com.ddwl.order.service.dto.CreateOrderDto;
import com.ddwl.order.service.dto.OrderSkuListDto;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.goods.SupplierBo;
import com.ddwl.schema.bo.order.OrderListApiBo;
import com.ddwl.schema.bo.order.QueryOrderAdderListBo;
import com.ddwl.schema.bo.order.ShopDeliveryBo;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.base.RestVo;
import com.ddwl.schema.vo.gate.RegionVo;
import com.ddwl.schema.vo.goods.SupplierVo;
import com.ddwl.schema.vo.order.OrderAddrVo;
import com.ddwl.schema.vo.order.OrderInfoVo;
import com.ddwl.schema.vo.shop.ShopVo;
import com.ddwl.schema.vo.user.UserAddrVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类OrderAddresServer.java的实现描述：订单收货地址处理
 *
 * @author zach
 * @Date :2020-06-02 14:23.
 */
@Service
@RefreshScope
@Slf4j
public class OrderAddressServer {

    @Resource
    private UserApi userApi;
    @Resource
    private GoodsApi goodsApi;
    @Resource
    private OrderAddrDao orderAddrDao;
    @Resource
    private GateApi gateApi;
    @Resource
    private ShopApi shopApi;
    @Resource
    private OrderInfoServer orderInfoServer;
    /**
     * 分页查询订单包含商品信息
     * @param boPageBo
     * @return
     */
    public PageVo<OrderAddrVo> getPage(PageBo<QueryOrderAdderListBo> boPageBo){
        PageHelper.startPage(boPageBo.getPage(),boPageBo.getPageSize(), MySqlUtil.orderBy(boPageBo.getSort(),boPageBo.isAsc()));
        PageInfo info = new PageInfo(orderAddrDao.queryOrderAddrs(boPageBo.getParam()));
        List<OrderAddrVo> list = BeanConverUtils.convertBeanList(info.getList(),OrderAddrVo.class);
        return new PageVo<>(info.getTotal(),boPageBo.getPage(),boPageBo.getPageSize(),list);
    }


    /**
     * 订单整单发货
     * @param deliveryBo
     */
    public void orderDelivery(ShopDeliveryBo deliveryBo){
        OrderAddr  addr = new OrderAddr();
        addr.setDeliveryTime(Instant.now());
        addr.setLogisticsName(deliveryBo.getLogisticsName());
        addr.setLogisticsCode(deliveryBo.getLogisticsCode());
        addr.setLogisticsNo(deliveryBo.getLogisticsNo());
        addr.setDeliveryType(deliveryBo.getDeliveryType());
        addr.setType(1);
        addr.setDeliveryStatus(OrderEnum.DeliveryStatus.START_DELIVERY.getCode());
        addr.setStatus(OrderEnum.OrderStatus.SEND.getCode());
        orderAddrDao.updateOrderAdderByOrderId(addr,deliveryBo.getOrderId());
    }

    /**
     * 分页查询待发货订单包含商品信息api
     * @param boPageBo
     * @return
     */
    public PageVo<OrderAddrVo> getApiPage( PageBo<OrderListApiBo> boPageBo){
        PageHelper.startPage(boPageBo.getPage(),boPageBo.getPageSize(), MySqlUtil.orderBy(boPageBo.getSort(),boPageBo.isAsc()));
        if(boPageBo.getParam()==null){
            boPageBo.setParam(new OrderListApiBo());
        }
        OrderListApiBo bo=boPageBo.getParam();
        ParamException.isTrue(bo.getAppId()==null,"appID为空");
        ParamException.isTrue(bo.getTimestamp()==null,"请求时间为空");
        SupplierBo supplierBo=new SupplierBo();
        supplierBo.setAppId(bo.getAppId());
        RestVo<PageVo<SupplierVo>> pageVoRestVo = goodsApi.querySupplierCategory(supplierBo);
        List<SupplierVo> data = pageVoRestVo.getResult().getData();
        ParamException.isTrue(data==null||data.size()==0,"appID不存在");
        List<String>supplierList= data.stream().map(supplierVo -> supplierVo.getId()).collect(Collectors.toList());
        bo.setSupplierList(supplierList);
        PageInfo info = new PageInfo(orderAddrDao.queryApiOrderAddr(bo));
        List<OrderAddrVo> list = BeanConverUtils.convertBeanList(info.getList(),OrderAddrVo.class);
        PageVo<OrderAddrVo> orderAddrVoPageVo = new PageVo<>(info.getTotal(), boPageBo.getPage(), boPageBo.getPageSize(), list);
        return orderAddrVoPageVo;
    }


    public void orderPayConfirm(OrderInfo orderInfo){
        OrderAddr update = new OrderAddr();
        update.setPayTime(orderInfo.getPayTime());
        update.setType(OrderEnum.AddrOrderStatus.UN_SEND.getCode());
        update.setStatus(orderInfo.getStatus());
        update.setDeliveryStatus(OrderEnum.DeliveryStatus.STOCK.getCode());
        if(OrderEnum.DeliveryType.ZT.getCode().equals(orderInfo.getDeliveryType())){
            update.setDeliveryStatus(OrderEnum.DeliveryStatus.STOCK_COMPLETE.getCode());
            update.setDeliveryCode(RandomUtil.randomNumbers(4));
        }
        orderAddrDao.updateOrderAdderByOrderId(update,orderInfo.getId());
    }

    public String createOrderAddr(CreateOrderDto createOrderDto, OrderInfo orderInfo){
        OrderAddr orderAddr = null;
        if(OrderEnum.DeliveryType.ZT.getCode().equals(createOrderDto.getDeliveryType())){
            ShopVo shopVo = shopApi.getShopForApi(orderInfo.getShopId()).getResult();
            orderAddr = new OrderAddr();
            orderAddr.setAddress(shopVo.getAddress());
            orderAddr.setReceiver(createOrderDto.getUserName());
            orderAddr.setProvinceName(shopVo.getProvinceName());
            orderAddr.setCityName(shopVo.getCityName());
            orderAddr.setDistrictName(shopVo.getDistrictName());
            orderAddr.setRegionId(shopVo.getRegionId());
            orderAddr.setType(OrderEnum.AddrOrderStatus.SEND.getCode());
            orderAddr.setMobile(createOrderDto.getSkuLists().get(0).getMobile());
        }else {
            UserAddrVo userAddrVo = userApi.getUserAdderDetail(createOrderDto.getUserAdderId()).getResult();
            ParamException.isNull(userAddrVo,"地址信息不正确");
            orderAddr = BeanConverUtils.convertBean(userAddrVo,OrderAddr.class,"id");
            orderAddr.setType(OrderEnum.AddrOrderStatus.UN_SEND.getCode());
        }
        orderAddr.setDeliveryType(createOrderDto.getDeliveryType());
        orderAddr.setOrderId(orderInfo.getId());
        orderAddr.setUserId(orderInfo.getUserId());
        orderAddr.setLastSendSmsTime(DateUtil.getTimesMorning(Instant.now(),-2));
        //orderAddr.setDeliveryStatus(OrderEnum.DeliveryStatus.TACK.getCode());
        orderAddr.setPayTime(orderInfo.getPayTime());
        if (null != orderInfo.getPayTime()) {
            orderAddr.setPayTime(orderInfo.getPayTime());
        }
        for (OrderSkuListDto orderSpu:createOrderDto.getSkuLists()) {
            OrderAddr orderAddrNew = BeanConverUtils.convertBean(orderAddr, OrderAddr.class);
            orderAddrNew.setSkuId(orderSpu.getSkuId());
            orderAddrNew.setItemId(orderSpu.getItemId());
            orderAddrNew.setItemCount(orderSpu.getSkuQty());
            orderAddrNew.setStatus(orderInfo.getStatus());
            if(StrUtil.isNotEmpty(orderSpu.getMobile())&&OrderEnum.DeliveryType.ZT.getCode().equals(createOrderDto.getDeliveryType())){
                orderAddrNew.setMobile(orderSpu.getMobile());
            }
            orderAddrDao.insert(orderAddrNew);
        }
        return orderAddr.getRegionId();
    }


    public OrderAddrVo getOrderAddr(String orderId){
        OrderAddr orderAddr = new OrderAddr();
        orderAddr.setOrderId(orderId);
        OrderAddrVo orderAddrVo = BeanConverUtils.convertBean(orderAddrDao.selectOne(orderAddr), OrderAddrVo.class);
        if(orderAddrVo == null) {
            throw new CommonException(ExceptionCode.DATA_NOT_EXISTS);
        }
        if (!StringUtils.hasText(orderAddrVo.getLogisticsCode())) {
            orderAddrVo.setLogisticsCode(orderAddrVo.getLogisticsName());
        }
        return orderAddrVo;
    }

    public OrderAddrVo getShopOrderAddr(String orderId,String shopId){
        OrderInfoVo orderInfo = orderInfoServer.getOrderInfoVo(orderId);
        ParamException.isNull(orderInfo,"订单不存在");
        //IllegalException.isFalse(orderInfo.getShopId().equals(shopId),"您无权访问该数据");
        OrderAddr orderAddr = new OrderAddr();
        orderAddr.setOrderId(orderId);
        OrderAddrVo orderAddrVo = BeanConverUtils.convertBean(orderAddrDao.selectOne(orderAddr),OrderAddrVo.class);
        if(orderAddrVo!=null){
            orderAddrVo.setDeliveryCode(null);
        }
        return  orderAddrVo;
    }

    public List<OrderAddrVo> getOrderAddrs(String orderId){
        OrderAddr orderAddr = new OrderAddr();
        orderAddr.setOrderId(orderId);
        return  BeanConverUtils.convertBeanList(orderAddrDao.select(orderAddr),OrderAddrVo.class);
    }

    public void updateOrderAddr(OrderAddr addr, OrderInfo orderInfo){
        List<OrderSpu> orderSpus = JSON.parseArray(orderInfo.getSkuSnapshoot(), OrderSpu.class);
        OrderAddr orderAddr = BeanConverUtils.convertBean(addr,OrderAddr.class,"id");
        RegionVo regionVoRestVo = gateApi.geoRegion(addr.getRegionId()).getResult();
        orderAddr.setProvinceName(regionVoRestVo.getProvinceName());
        orderAddr.setCityName(regionVoRestVo.getCityName());
        orderAddr.setDistrictName(regionVoRestVo.getDistrictName());
        //orderAddr.setType(0);
        //List<OrderAddr> list =new ArrayList<>();
        if (orderSpus!=null&&orderSpus.size()!=0){
            for (OrderSpu orderSpu:orderSpus) {
                OrderAddr orderAddrNew = BeanConverUtils.convertBean(orderAddr, OrderAddr.class);
                orderAddrNew.setSkuId(orderSpu.getSkuId());
                orderAddrNew.setItemId(orderSpu.getItemId());
                orderAddrNew.setItemCount(orderSpu.getSkuQty());
                orderAddrNew.setStatus(orderInfo.getStatus());
                //list.add(orderAddrNew);
                orderAddrDao.insert(orderAddrNew);
            }
        }
    }

}
